from Transaction import Transaction
import random
from Crypto.Random import get_random_bytes
from Crypto_modified import ECDSA
from Crypto.Hash import SHA256
import rlp
import json


'''生成交易'''
def generate(i):
    sender = hex(random.randint(1, random.getrandbits(160)))
    data = get_random_bytes(256)
    t = Transaction(nonce=random.randint(1, random.getrandbits(256)))
    t.value = 0
    t.receiveAddress = hex(random.randint(1, random.getrandbits(160)))
    t.data = data
    t.blockLimit = 500 + i
    t_list = [t.nonce, t.gasPrice, t.gas, t.blockLimit, t.receiveAddress, t.value, t.data, t.chainId, t.groupId]
    t.vrs = ECDSA.sign(SHA256.new(rlp.encode(t_list)).hexdigest())[0]
    t_list = t_list + t.vrs
    t.hashWith = SHA256.new(rlp.encode(t_list)).hexdigest()
    t.sender = sender
    return t


'''交易编码'''
def encode(tx):
    return json.dumps(tx.to_dict())


'''交易签名'''
def sign(tx):
    return ECDSA.sign(tx.hashWith)


'''交易进池'''
def push_to_pool(tx, pool):
    pool.append(encode(tx), sign(tx))
